<template>
  <div class="app-container">
    <!-- 筛选条件、新增按钮和导出按钮 -->
    <div class="filter-actions-container">
      <el-row :gutter="20" justify="space-between" align="middle">
        <!-- 左侧：筛选条件 -->
        <el-col :span="16">
          <el-form :model="queryParams" inline>
            <el-form-item label="园区名称">
              <el-select
                  v-model="queryParams.parkName"
                  placeholder="请选择"
                  clearable
                  filterable
              >
                <el-option
                    v-for="item in parkOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>

        <!-- 右侧：操作按钮 -->
        <el-col :span="8" style="display: flex; justify-content: flex-end; gap: 10px;">
          <el-button type="primary" @click="handleAdd">新增园区</el-button>
          <el-dropdown @command="handleExportCommand" trigger="click">
            <el-button type="primary">
              导出数据<el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="excel">Excel格式</el-dropdown-item>
                <el-dropdown-item command="word">Word格式</el-dropdown-item>
                <el-dropdown-item command="pdf">PDF格式</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
      </el-row>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading"><Loading /></el-icon>
      加载中...
    </div>

    <!-- 数据表格 -->
    <el-table v-else :data="tableData" border stripe>
      <el-table-column prop="parkId" label="园区编号" width="120" />
      <el-table-column prop="parkName" label="园区名称" />
      <el-table-column prop="contact" label="联系人" />
      <el-table-column prop="phone" label="联系电话" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="text" size="small" @click="handleDetail(scope.row)">详情</el-button>
          <el-button type="text" size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
              style="color: #f56c6c"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态提示 -->
    <div v-if="!loading && tableData.length === 0" class="empty-state">
      <el-empty description="暂无数据" />
    </div>

    <!-- 分页组件 -->
    <div v-if="!loading && tableData.length > 0" class="pagination-container">
      <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
      />
    </div>

    <!-- 数据录入对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="800px"
        destroy-on-close
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="园区名称" prop="parkName">
              <el-input v-model="formData.parkName" clearable :disabled="isDetailMode" />
            </el-form-item>

            <el-form-item label="联系人" prop="contact">
              <el-input v-model="formData.contact" :disabled="isDetailMode" />
            </el-form-item>

            <el-form-item label="联系方式" prop="phone">
              <el-input v-model="formData.phone" :disabled="isDetailMode" />
            </el-form-item>

            <el-form-item label="省/市/区" prop="address">
              <el-cascader
                  v-model="formData.address"
                  :options="areaOptions"
                  :props="areaProps"
                  placeholder="请选择省/市/区"
                  style="width: 100%"
                  :disabled="isDetailMode"
              />
            </el-form-item>

            <el-form-item label="详细地址" prop="detailAddress">
              <el-input
                  v-model="formData.detailAddress"
                  placeholder="请输入详细地址"
                  clearable
                  :disabled="isDetailMode"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="总面积(㎡)" prop="totalArea">
              <el-input-number
                  v-model="formData.totalArea"
                  :min="0"
                  :controls="false"
                  class="full-width"
                  :disabled="isDetailMode"
              />
            </el-form-item>

            <el-form-item label="可用面积(㎡)" prop="usableArea">
              <el-input-number
                  v-model="formData.usableArea"
                  :min="0"
                  :controls="false"
                  :disabled="isDetailMode"
              />
            </el-form-item>

            <el-form-item label="园区图片">
              <el-upload
                  action="#"
                  list-type="picture-card"
                  :auto-upload="false"
                  :limit="3"
                  :disabled="isDetailMode"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">{{ isDetailMode ? '关闭' : '取消' }}</el-button>
        <el-button v-if="!isDetailMode" type="primary" @click="handleSubmit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Plus } from '@element-plus/icons-vue'
import { ArrowDown } from '@element-plus/icons-vue'
import { Loading } from '@element-plus/icons-vue'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import { utils, writeFile } from 'xlsx'
import { Document, Paragraph, Table, TableRow, TableCell, WidthType, HeadingLevel } from "docx";
import * as docx from "docx";
import { saveAs } from "file-saver";
import { regionData } from 'element-china-area-data'
import axios from 'axios';

// 设置基础URL（从环境变量获取，自动适配环境）
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
});

export default {
  components: { Plus, ArrowDown,Loading },
  data() {
    return {
      loading: false,
      tableData: [],
      // 分页相关数据
      currentPage: 1,
      pageSize: 5,
      total: 0,

      // 地址选择配置
      areaOptions: regionData,
      areaProps: {
        value: 'value',
        label: 'label',
        children: 'children',
        checkStrictly: true
      },

      // 表单相关数据
      dialogVisible: false,
      dialogType: 'add', // 'add' | 'edit' | 'detail'
      formData: {
        parkName: '',
        contact: '',
        phone: '',
        address: [],
        detailAddress: '',
        totalArea: null,
        usableArea: null
      },
      formRules: {
        parkName: [{ required: true, message: '必填项', trigger: 'blur' }],
        contact: [{ required: true, message: '必填项', trigger: 'blur' }],
        phone: [
          { required: true, message: '必填项', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' }
        ],
        totalArea: [{ required: true, message: '必填项', trigger: 'blur' }],
        address: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              value.length === 3 ? callback() : callback(new Error('请选择完整的省市区'))
            }
          }
        ],
        detailAddress: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ]
      },
      queryParams: {
        parkName: null
      },
      parkOptions: [] // 初始化为空数组，将通过API获取
    }
  },
  computed: {
    isDetailMode() {
      return this.dialogType === 'detail'
    },
    dialogTitle() {
      const titles = {
        'add': '园区信息录入',
        'edit': '修改园区信息',
        'detail': '园区详情'
      }
      return titles[this.dialogType] || '园区信息'
    }
  },
  methods: {
    async fetchParks() {
      this.loading = true;
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          parkName: this.queryParams.parkName|| undefined
        };

        console.log('请求参数:', params);

        const response = await api.get('/api/resource-list', {params});
        console.log('API响应数据:', response.data);

        this.tableData = response.data.list||[];
        this.total = response.data.total||0;
      } catch (error) {
        console.error('获取园区数据失败:', error);
        if (error.response) {
          console.error('响应状态:', error.response.status);
          console.error('响应数据:', error.response.data);
        }
        this.$message.error('获取数据失败');
      } finally {
        this.loading = false;
      }
    },

    // 添加缺失的方法
    async fetchParkOptions() {
      try {
        const response = await api.get('/api/resource-list/options');
        this.parkOptions = response.data;
      } catch (error) {
        console.error('获取园区选项失败:', error);
        // 如果API不可用，使用默认选项
        this.parkOptions = [
          { value: '科技园区', label: '科技园区' },
          { value: '创新园区', label: '创新园区' },
          { value: '生态园区', label: '生态园区' }
        ];
      }
    },

    // 创建园区
    async createPark() {
      try {
        const response = await api.post('/api/resource-list', this.formData);
        console.log('创建成功:', response.data);
        this.fetchParks(); // 刷新列表
      } catch (error) {
        if (error.response && error.response.status === 409) {
          this.$message.error('园区名称已存在');
        } else {
          this.$message.error('创建失败');
        }
      }
    },

    // 更新园区
    async updatePark(id) {
      try {
        const response = await api.put(`/api/resource-list/${id}`, this.formData);
        console.log('更新成功:', response.data);
        this.fetchParks(); // 刷新列表
      } catch (error) {
        if (error.response && error.response.status === 409) {
          this.$message.error('园区名称已存在');
        } else {
          this.$message.error('更新失败');
        }
      }
    },

    // 删除园区
    async deletePark(id) {
      try {
        await api.delete(`/api/resource-list/${id}`);
        this.fetchParks(); // 刷新列表
      } catch (error) {
        if (error.response && error.response.status === 409) {
          this.$message.error('该园区存在关联数据，无法删除');
        } else {
          this.$message.error('删除失败');
        }
      }
    },

    handleDelete(row) {
      this.$confirm('确定要删除该园区吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.deletePark(row.parkId);
        this.$message.success('删除成功');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handleEdit(row) {
      this.dialogType = 'edit';
      this.dialogVisible = true;

      // 填充表单数据
      this.formData = {
        parkId: row.parkId, // 确保包含 parkId 用于更新
        parkName: row.parkName,
        contact: row.contact,
        phone: row.phone,
        address: row.address || [row.provinceCode, row.cityCode, row.districtCode],
        detailAddress: row.detailAddress,
        totalArea: row.totalArea,
        usableArea: row.usableArea,
      };
    },


    handleDetail(row) {
      this.dialogType = 'detail';
      this.dialogVisible = true;

      // 填充表单数据
      this.formData = {
        parkId: row.parkId,
        parkName: row.parkName,
        contact: row.contact,
        phone: row.phone,
        address: row.address || [row.provinceCode, row.cityCode, row.districtCode],
        detailAddress: row.detailAddress,
        totalArea: row.totalArea,
        usableArea: row.usableArea,
      };
    },

    handleExportCommand(command) {
      if (this.tableData.length === 0) {
        this.$message.warning('没有可导出的数据')
        return
      }

      switch (command) {
        case 'excel':
          this.exportExcel()
          break
        case 'word':
          this.exportWord()
          break
        case 'pdf':
          this.exportPDF()
          break
      }
    },

    exportExcel() {
      const data = this.formatExportData()
      const worksheet = utils.json_to_sheet(data)
      const workbook = utils.book_new()
      utils.book_append_sheet(workbook, worksheet, '园区数据')
      writeFile(workbook, `园区数据_${this.getTimeStamp()}.xlsx`)
    },

    exportWord() {
      try {
        const doc = new Document({
          sections: [{
            children: [
              new Paragraph({
                text: "园区数据报表",
                heading: HeadingLevel.HEADING_1,
                alignment: "center",
                spacing: {after: 200}
              }),
              new Table({
                width: {size: 100, type: WidthType.PERCENTAGE},
                borders: {
                  top: {style: "single", size: 4, color: "#AAAAAA"},
                  bottom: {style: "single", size: 4, color: "#AAAAAA"},
                  left: {style: "single", size: 4, color: "#AAAAAA"},
                  right: {style: "single", size: 4, color: "#AAAAAA"},
                  insideHorizontal: {style: "single", size: 2, color: "#CCCCCC"},
                  insideVertical: {style: "single", size: 2, color: "#CCCCCC"}
                },
                rows: [
                  // 表头行
                  new TableRow({
                    children: [
                      new TableCell({children: [new Paragraph("园区编号")], shading: {fill: "#F2F2F2"}}),
                      new TableCell({children: [new Paragraph("园区名称")], shading: {fill: "#F2F2F2"}}),
                      new TableCell({children: [new Paragraph("联系人")], shading: {fill: "#F2F2F2"}}),
                      new TableCell({children: [new Paragraph("联系电话")], shading: {fill: "#F2F2F2"}}),
                      new TableCell({children: [new Paragraph("详细地址")], shading: {fill: "#F2F2F2"}}),
                      new TableCell({children: [new Paragraph("总面积(㎡)")], shading: {fill: "#F2F2F2"}}),
                      new TableCell({children: [new Paragraph("可用面积(㎡)")], shading: {fill: "#F2F2F2"}})
                    ]
                  }),
                  // 数据行
                  ...this.tableData.map(item => new TableRow({
                    children: [
                      new TableCell({children: [new Paragraph(item.parkId)]}),
                      new TableCell({children: [new Paragraph(item.parkName)]}),
                      new TableCell({children: [new Paragraph(item.contact)]}),
                      new TableCell({children: [new Paragraph(item.phone)]}),
                      new TableCell({children: [new Paragraph(`${item.address.join('/')} ${item.detailAddress}`)]}),
                      new TableCell({children: [new Paragraph(String(item.totalArea))]}),
                      new TableCell({children: [new Paragraph(String(item.usableArea))]})
                    ]
                  }))
                ]
              }),
              new Paragraph({
                text: `导出时间: ${new Date().toLocaleString()}`,
                alignment: "right",
                spacing: {before: 200}
              })
            ]
          }]
        });

        docx.Packer.toBlob(doc).then(blob => {
          saveAs(blob, `园区数据_${this.getTimeStamp()}.docx`);
        });
      } catch (error) {
        console.error("导出Word失败:", error);
        this.$message.error("导出Word失败");
      }
    },

    exportPDF() {
      const pdfContainer = document.createElement('div')
      pdfContainer.style.position = 'absolute'
      pdfContainer.style.left = '-9999px'
      pdfContainer.style.width = '800px'
      pdfContainer.style.padding = '20px'
      pdfContainer.style.backgroundColor = '#fff'

      pdfContainer.innerHTML = `
    <h1 style="text-align: center; margin-bottom: 20px;">园区数据报表</h1>
    <table border="1" cellspacing="0" cellpadding="5" style="width: 100%; border-collapse: collapse;">
      <thead>
        <tr style="background-color: #f5f7fa;">
          <th>园区编号</th>
          <th>园区名称</th>
          <th>联系人</th>
          <th>联系电话</th>
          <th>省市区</th>
          <th>详细地址</th>
          <th>总面积(㎡)</th>
          <th>可用面积(㎡)</th>
        </tr>
      </thead>
      <tbody>
        ${this.tableData.map(item => `
          <tr>
            <td>${item.parkId}</td>
            <td>${item.parkName}</td>
            <td>${item.contact}</td>
            <td>${item.phone}</td>
            <td>${item.address.join('/')}</td>
            <td>${item.detailAddress}</td>
            <td>${item.totalArea}</td>
            <td>${item.usableArea}</td>
          </tr>
        `).join('')}
      </tbody>
    </table>
    <div style="text-align: right; margin-top: 20px; font-size: 12px;">
      导出时间: ${new Date().toLocaleString()}
    </div>
  `

      document.body.appendChild(pdfContainer)

      html2canvas(pdfContainer, {
        scale: 2,
        useCORS: true,
        logging: false
      }).then(canvas => {
        const imgData = canvas.toDataURL('image/jpeg', 0.9)
        const imgWidth = 210
        const imgHeight = (canvas.height * imgWidth) / canvas.width

        const pdf = new jsPDF('p', 'mm', 'a4')
        pdf.addImage(imgData, 'JPEG', 0, 0, imgWidth, imgHeight)
        pdf.save(`园区数据_${this.getTimeStamp()}.pdf`)

        document.body.removeChild(pdfContainer)
      }).catch(error => {
        console.error('导出PDF失败:', error)
        this.$message.error('导出PDF失败')
        document.body.removeChild(pdfContainer)
      })
    },

    formatExportData() {
      return this.tableData.map(item => ({
        '园区编号': item.parkId,
        '园区名称': item.parkName,
        '联系人': item.contact,
        '联系电话': item.phone,
        '省市区': item.address.join('/'),
        '详细地址': item.detailAddress,
        '总面积(㎡)': item.totalArea,
        '可用面积(㎡)': item.usableArea
      }))
    },

    getTimeStamp() {
      const now = new Date()
      return now.toISOString().slice(0, 19).replace(/[-T:]/g, '')
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchParks();
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchParks();
    },

    handleQuery() {
      this.currentPage = 1;
      this.fetchParks();
    },

    resetQuery() {
      this.queryParams = {
        parkName: null
      }
      this.currentPage = 1;
      this.fetchParks();
    },

    handleAdd() {
      this.dialogType = 'add'
      this.resetForm()
      this.dialogVisible = true
    },

    resetForm() {
      this.formData = {
        parkName: '',
        contact: '',
        phone: '',
        address: [],
        detailAddress: '',
        totalArea: null,
        usableArea: null
      }
    },

    async handleSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          try {

            // 处理地址字段 - 确保是普通数组而不是 Proxy
            const address = this.formData.address ? [...this.formData.address] : [];

            // 构建请求数据
            const requestData = {
              parkName: this.formData.parkName,
              contact: this.formData.contact,
              phone: this.formData.phone,
              address: address,
              detailAddress: this.formData.detailAddress,
              totalArea: Number(this.formData.totalArea),
              usableArea: this.formData.usableArea ? Number(this.formData.usableArea) : null
            };

            console.log('发送数据:', JSON.parse(JSON.stringify(requestData)));

            let response;
            if (this.dialogType === 'add') {
              response = await api.post('/api/resource-list', requestData);
            } else {
              if (!this.formData.parkId) {
                throw new Error('parkId 不存在');
              }
              response = await api.put(`/api/resource-list/${this.formData.parkId}`, requestData);
            }

            console.log('响应:', response.data);
            this.dialogVisible = false;
            this.fetchParks();
            this.$message.success('操作成功');
          } catch (error) {
            console.error('操作失败详情:', error);
            if (error.response) {
              console.error('状态码:', error.response.status);
              console.error('响应数据:', error.response.data);
            } else if (error.request) {
              console.error('未收到响应:', error.request);
            } else {
              console.error('错误信息:', error.message);
            }
            this.$message.error('操作失败: ' + (error.response?.data?.error || error.message));
          }
        }
      });
    }
  },
  mounted() {
    this.fetchParks();
    this.fetchParkOptions(); // 现在这个方法已定义
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-actions-container {
  margin-bottom: 20px;
}

.el-form--inline .el-form-item {
  margin-right: 10px;
  margin-bottom: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.mb-4 {
  margin-bottom: 1rem;
}

.full-width {
  width: 100%;
}

:deep(.el-upload) {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  flex-direction: column;
  gap: 10px;
}

.empty-state {
  margin-top: 50px;
}
</style>